package com.lianqi.emcpframework.core.generator;

import lombok.extern.slf4j.Slf4j;

import java.util.Random;

/**
 * @program emcp-framework
 * @ClassName SnowflakeIdGenerator
 * @description: 雪花算法id生成器
 * 第一位为未使用，接下来的41位为毫秒级时间(41位的长度可以使用69年)，
 * 然后是5位datacenterId和5位workerId(10位的长度最多支持部署1024个节点)，
 * 最后12位是毫秒内的计数（12位的计数顺序号支持每个节点每毫秒产生4096个ID序号）
 * 一共加起来刚好64位，为一个Long型。(转换成字符串长度为18)
 * @author: sky
 * @create: 2018/11/14 10:35
 */
@Slf4j
public class SnowflakeIdGenerator {

    private long workerId;
    private long dataCenterId;
    private long sequence = 0L;

    private long twepoch = 1288834974657L;

    private long workerIdBits = 5L;
    private long dataCenterIdBits = 5L;
    private long maxWorkId = -1L ^ (-1L << workerIdBits);
    private long maxDataCenterId = -1L ^ (-1L << dataCenterIdBits);
    private long sequenceBits = 12L;

    private long workerIdShift = sequenceBits;
    private long dataCenterIdShift = sequenceBits + workerIdBits;
    private long timestampLeftShift = sequenceBits + workerIdBits + dataCenterIdBits;
    private long sequenceMask = -1L ^ (-1L << sequenceBits);

    private long lastTimestamp = -1L;
    static final int BOUND = 31;

    private static final SnowflakeIdGenerator generator;

    static {
        Random random = new Random();
        long workerId = Long.getLong("id-worker",random.nextInt(BOUND));
        long dataCenterId = Long.getLong("id-dataCenter",random.nextInt(BOUND));
        generator = new SnowflakeIdGenerator(workerId,dataCenterId);

    }

    public static SnowflakeIdGenerator getInstance(){
        return generator;
    }

    public SnowflakeIdGenerator(long workerId, long dataCenterId) {
        if (workerId > maxWorkId || workerId < 0){
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0",maxWorkId));
        }
        if (dataCenterId > maxDataCenterId || dataCenterId < 0){
            throw new IllegalArgumentException(String.format("dataCenter Id can't be greater than %d or less than 0",maxDataCenterId));
        }
        this.workerId = workerId;
        this.dataCenterId = dataCenterId;
        log.info("worker starting. timestamp left shift {}, datacenter id bits {}, worker id bits {}, sequence bits {}, workerid {}", timestampLeftShift, dataCenterIdBits, workerIdBits, sequenceBits, workerId);
    }

    public synchronized long nextId(){
        long timestamp = timeGen();

        if (timestamp < lastTimestamp){
            log.error("clock is moving backwards.  Rejecting requests until {}.", lastTimestamp);
            throw new UnsupportedOperationException(String.format("Clock moved backwards.  Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
        }
        if (lastTimestamp == timestamp){
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }else {
                sequence = 0L;
            }
        }
        lastTimestamp = timestamp;
        return ((timestamp - twepoch) << timestampLeftShift) | (dataCenterId << dataCenterIdShift) | (workerId << workerIdShift) | sequence;
    }

    protected long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp){
            timestamp = timeGen();
        }
        return timestamp;
    }

    protected long timeGen() {
        return System.currentTimeMillis();
    }

}
